package org.internna.expensetracker.model.budget;

import java.util.Set;
import java.util.Locale;
import java.util.HashSet;
import java.math.BigDecimal;
import javax.persistence.OneToMany;
import javax.persistence.ManyToOne;
import javax.persistence.FetchType;
import javax.persistence.CascadeType;
import javax.validation.constraints.Min;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import org.internna.expensetracker.model.Subcategory;
import org.internna.expensetracker.model.budget.CategoryBudget;
import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.roo.addon.serializable.RooSerializable;

@RooJavaBean
@RooToString
@RooEntity
@RooSerializable
public class MonthlyBudget implements Comparable<MonthlyBudget> {

	private static final long serialVersionUID = -8182308667263709400L;

	@NotNull
    @ManyToOne(fetch = FetchType.EAGER)
    private Budget budget;

    @NotNull
    @Min(0L)
    @Max(11L)
    private Integer budgetedMonth;

    @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "monthlyBudget")
    private Set<CategoryBudget> budgets = new HashSet<CategoryBudget>();

	@Override public int compareTo(MonthlyBudget other) {
		return other == null ? 1 : budgetedMonth == null ? other.budgetedMonth == null ? 0 : -1 : other.budgetedMonth == null ? 1 : budgetedMonth.compareTo(other.budgetedMonth);
	}

	public final CategoryBudget getBudget(Locale locale, Subcategory subcategory) {
		CategoryBudget budget = null;
		if ((locale != null) & (subcategory != null)) {
			for (CategoryBudget categoryBudget : budgets) {
				if (categoryBudget.getLocale().equals(locale) & categoryBudget.getCategory().equals(subcategory)) {
					budget = categoryBudget;
				}
			}
		}
		return budget;
	}

	public final BigDecimal getAlloted(Locale locale, Subcategory subcategory) {
		CategoryBudget budget = getBudget(locale, subcategory);
		return budget == null ? BigDecimal.ZERO : budget.getExpectedAmount();
	}

}
